﻿using Aspose.Cells;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using Microsoft.AspNetCore.Hosting;
using OpenHtmlToPdf;
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using Rectangle = iTextSharp.text.Rectangle;

namespace SportsPlatform.Helpers
{
    public class PDFHelper
    {
        /// <summary>
        /// html转pdf
        /// </summary>
        /// <param name="html"></param>
        /// <param name="watermarkimg">水印</param>
        /// <param name="Name">文件名字</param>
        /// <returns></returns>
        public static string HtmlToPdf(string html, string watermarkimg, string Name)
        {
            var document = Pdf.From(html)
                .OfSize(PaperSize.A4)  //大小，这里选A4纸大小
                .WithGlobalSetting("margin.top", "0.4cm")//设置全局样式
                .EncodedWith("utf-8");

            //此属性的值在32位进程中为4，在64位进程中为8。
            if (IntPtr.Size == 8)
            {
                document = document.WithObjectSetting("load.zoomFactor", "1.5");
            }
            var result = document.Content();
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "/UpLode/" + DateTime.Now.ToString("yyyyMMdd");//路径
            FolderHelper.AddFolder(filePath);
            string fileName = Name + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
            //通过stream把html写入到pdf文件中
            FileStream fs = new FileStream(filePath + "/" + fileName, FileMode.Create, FileAccess.Write);
            fs.Write(result, 0, result.Length);
            fs.Close();
            //加水印
            string filewatermarkPath = filePath + "/" + Name + DateTime.Now.ToString("yyyyMMddHHmmssffffff") + ".pdf";
            setWatermark(filePath + "/" + fileName, filewatermarkPath, watermarkimg);

            if (File.Exists(filePath + "/" + fileName))
                File.Delete(filePath + "/" + fileName);
            return filewatermarkPath;
        }

        /// <summary>
        /// 添加普通偏转角度文字水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="waterMarkName"></param>
        /// <param name="permission"></param>
        public static void setWatermark(string inputfilepath, string outputfilepath, string waterMarkName)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(inputfilepath);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                // 设置密码   
                //pdfStamper.SetEncryption(false,userPassWord, ownerPassWord, permission); 
                int total = pdfReader.NumberOfPages + 1;
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
                float width = psize.Width;
                float height = psize.Height;
                PdfContentByte content;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState gs = new PdfGState();
                for (int i = 1; i < total; i++)
                {
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                    //透明度
                    gs.FillOpacity = 0.3f;
                    content.SetGState(gs);
                    //content.SetGrayFill(0.3f);
                    //开始写入文本
                    content.BeginText();
                    content.SetColorFill(BaseColor.LIGHT_GRAY);
                    content.SetFontAndSize(font, 100);
                    content.SetTextMatrix(0, 0);
                    content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2 - 50, height / 2 - 50, 55);
                    //content.SetColorFill(BaseColor.BLACK);
                    //content.SetFontAndSize(font, 8);
                    //content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, 0, 0, 0);
                    content.EndText();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {

                if (pdfStamper != null)
                    pdfStamper.Close();

                if (pdfReader != null)
                    pdfReader.Close();
            }
        }

        public static string DataTableToPDF(IWebHostEnvironment web, DataTable dataTable, string Name)
        {
            string excelpath = ExportHelper.DataTableToExcel(web, dataTable, Name);
            if (string.IsNullOrEmpty(excelpath))
            {
                return "";
            }


            Workbook workbook = new Workbook(excelpath);
            //PdfSaveOptions saveOptions = new PdfSaveOptions();
            //saveOptions.seton
            // workbook.Save(pdfpath, saveOptions);
            workbook.Save(excelpath, SaveFormat.Pdf);
            return excelpath;
        }
    }
}
